/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.database;

import com.codemagi.util.*;

/**
 * Supports SELECT only, returns query results as a com.codemagi.util.OrderedTable. 
 * The first field of a SELECT statement becomes the key, the second field is the value
 *
 * @version 1.0
 * @author August Detlefsen for CodeMagi, Inc.
 */
public class TableDataSourceBean extends DataSourceBean {
	
    // The result set of the db query represented as a OrderedTable
    protected OrderedTable queryResult = null;
	
    // The maximum number of rows that the result set will contain.
    private static final int MAX_ROWS = Integer.MAX_VALUE;
        

    /**
     * Constructor
     *
     * @param resourceName  The JNDI resource to connect to
     */
    public TableDataSourceBean( String resourceName ) {
	super(resourceName);
	log.debug("Constructing TableDataSourceBean");
    }
	
    
    /**
     * Creates an OrderedTable of Strings from the JDBC result set.     
     *
     * @return The OrderedTable representing the result set.
     */
    protected void create2DArray() {

	//estimate the number of rows in the result set
	int estNumRows = estimateNumRows();

	log.debug("TableDataSourceBean.createTable(): Est num rows in result: " + estNumRows);

	queryResult = new OrderedTable(estNumRows, 1);

        String key   = "";
	String value = "";

	int rowNum = 0;

        while ( nextResSetRow() ) {

	    key   = getRowSetItem( 1 );
	    value = getRowSetItem( 2 );
        	
	    log.debug("ROW: " + key + " - " + value );

	    queryResult.put(key, value);
	    
	    rowNum++;
	}

	if (rowNum != estNumRows) log.debug("ERROR: Estimate does not equal actual rows: " + rowNum);
    }


    /**
     * Returns the result of the query, as an OrderedTable
     */
    public OrderedTable getQueryResult() {
	return (queryResult == null) ? new OrderedTable() : queryResult ;
    }

}
